package io.xxx.omni.osc.sync

import com.alibaba.fastjson.JSONObject
import io.xxx.omni.osc.common.dateTimeFormatter
import io.xxx.omni.osc.common.toJSONObject
import io.xxx.omni.osc.common.toLocalDateTime
import io.xxx.omni.osc.domain.Document
import io.xxx.omni.osc.domain.DocumentType
import io.xxx.omni.osc.domain.PlatformIdentity
import io.xxx.omni.osc.domain.Store
import io.xxx.omni.osc.sdk.BbsClient
import org.springframework.stereotype.Component
import java.time.LocalDateTime

/**
 * 宝宝树
 */
// http://platform.meitun.com/apidoc/
abstract class BbsPagePorter : GenericPageDocumentPorter(), PlatformIdentity.BaoBaoShu {

    protected abstract val path: String

    override fun getResponse(context: JobContext, pageNo: Int, hasTotal: Boolean): JSONObject {
        val (store, startTime, endTime, parameter) = context
        val request = buildRequest(startTime, endTime, parameter, pageNo)
        val client = applicationContext.getBean(BbsClient::class.java)
        val response = client.execute(store, path, request)
        if (!response.getBoolean("isSuccess")) {
            throwException(context, request, response)
        }
        return response.getJSONObject("data")
    }

    protected abstract fun buildRequest(
        startTime: LocalDateTime,
        endTime: LocalDateTime,
        parameter: Any?,
        pageNo: Int,
    ): Map<String, Any>
}

@Component
class BbsTradePorter : BbsPagePorter() {

    override val documentType = DocumentType.TRADE

    override val path = "/order/orderInPage"

    override fun getParameters(store: Store): Pair<List<Any>, Boolean> = listOf("modified_time") to false

    override fun getCount(context: JobContext, response: JSONObject): Int = response.getInteger("totalCount")

    override fun buildDocuments(context: JobContext, response: JSONObject): List<Document> {
        return response
            .getJSONArray("list")
            .map {
                val value = it.toJSONObject()
                val sn = value.getString("code")
                val status = value.getString("status")
                val modified = (value.getLong("payTime") ?: value.getLong("createTime")).toLocalDateTime()
                Document(sn, status, modified, value)
            }
    }

    override fun buildRequest(
        startTime: LocalDateTime,
        endTime: LocalDateTime,
        parameter: Any?,
        pageNo: Int
    ): Map<String, Any> {
        return mapOf(
            "timeRange" to parameter!!,
            "startTime" to startTime.format(dateTimeFormatter),
            "endTime" to endTime.format(dateTimeFormatter),
            "pageNo" to pageNo,
            "pageSize" to pageSize,
        )
    }
}